package create

import (
	"context"
	"fmt"
	"github.com/elastic/go-elasticsearch/v8"
	"s13_elastic/es/document"
	"strconv"
	"time"
)

// CreateIndex 创建索引
func CreateIndex(client *elasticsearch.TypedClient, indexName string) {
	ok, err := client.Indices.Exists(indexName).Do(context.Background())
	if ok {
		fmt.Printf("index already exists")
		return
	}

	resp, err := client.Indices.
		Create(indexName).
		Do(context.Background())
	if err != nil {
		fmt.Printf("create index failed, err:%v\n", err)
		return
	}
	fmt.Printf("index:%#v\n", resp.Index)
}

// IndexDocument 创建一条 document 并添加到 my-review-1 的 index 中
func IndexDocument(client *elasticsearch.TypedClient) {
	// 定义 document 结构体对象
	d1 := document.Review{
		ID:      1,
		UserID:  147982601,
		Score:   5,
		Content: "这是一个好评！",
		Tags: []document.Tag{
			{1000, "好评"},
			{1100, "物超所值"},
			{9000, "有图"},
		},
		Status:      2,
		PublishTime: time.Now(),
	}

	// 添加文档
	resp, err := client.Index("my-review-1").
		Id(strconv.FormatInt(d1.ID, 10)).
		Document(d1).
		Do(context.Background())
	if err != nil {
		fmt.Printf("indexing document failed, err:%v\n", err)
		return
	}
	fmt.Printf("result:%#v\n", resp.Result)
}
